﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Text;
using System.Windows.Forms;
using Common.Utilities.Dispatcher;
using WindowsUserControl.UIUpdateWrapper;

namespace Workflows.Components.ETL
{
    public partial class WebCrawlerEditor : Form, IComponentEditor 
    {
        private WebRequestIntercepter _WebReqEngine=new WebRequestIntercepter();
        private object _ownerActivityNode;
        private WebCrawlerComponnet _WebCrawler;

        /// <summary>
        /// ctor
        /// </summary>
        public WebCrawlerEditor()
        {
            InitializeComponent();
            this._WebReqEngine.OnIntercepterStatusChanged += new IntercepterStatusChanged(_WebReqEngine_OnIntercepterStatusChanged);
            this._WebReqEngine.OnWebRequestIntercepted += new WebRequestIntercepted(_WebReqEngine_OnWebRequestIntercepted);
        }

        void _WebReqEngine_OnWebRequestIntercepted(WebRequest webRequest, WebResponse webResponse)
        {
            string url = webRequest.Protocol.ToString() + "://" + webRequest.BaseUrl;
            List<DataGridViewRow> rows=new List<DataGridViewRow>();
            if(webRequest.Parameters !=null && webRequest.Parameters.Count>0)
            {
                string urlParamStr = string.Empty;
                foreach(WebParameter webParam in webRequest.Parameters)
                {
                    if(webParam.ParemeterType==WebParameterType.Url)
                    {
                        if(urlParamStr.Length==0)
                        {
                            urlParamStr = "?";
                        }
                        if(urlParamStr.Length>1)
                        {
                            urlParamStr += "&";
                        }
                        urlParamStr += webParam.ParameterName + "=" + webParam.ParameterValue;
                    }

                    DataGridViewRow dr=new DataGridViewRow();
                    DataGridViewTextBoxCell cellName=new DataGridViewTextBoxCell();
                    cellName.Value = webParam.ParameterName;
                    dr.Cells.Add(cellName);
                    DataGridViewTextBoxCell cellValue = new DataGridViewTextBoxCell();
                    cellValue.Value = webParam.ParameterValue;
                    dr.Cells.Add(cellValue);
                    DataGridViewTextBoxCell cellType = new DataGridViewTextBoxCell();
                    cellType.Value = webParam.ParemeterType.ToString();
                    dr.Cells.Add(cellType);
                    rows.Add(dr);
                }
                url += urlParamStr;
            }
            new LabelUpdator(lbl_WebRequestUrl, string.Format("URL: {0}", url));
            new DataGridViewUpdator(this.dv_Parameters, rows.ToArray(), false);
            
            List<DataGridViewRow> rows2=new List<DataGridViewRow>();
            if(webRequest.Cookies !=null && webRequest.Cookies.Count>0)
            {
                foreach(Cookie cookie in webRequest.Cookies)
                {
                    DataGridViewRow dr=new DataGridViewRow();
                    DataGridViewTextBoxCell cellName=new DataGridViewTextBoxCell();
                    cellName.Value = cookie.Name;
                    dr.Cells.Add(cellName);
                    DataGridViewTextBoxCell cellDomain=new DataGridViewTextBoxCell();
                    cellDomain.Value = cookie.Domain;
                    dr.Cells.Add(cellDomain);
                    DataGridViewTextBoxCell cellValue=new DataGridViewTextBoxCell();
                    cellValue.Value = cookie.Value;
                    dr.Cells.Add(cellValue);
                    DataGridViewTextBoxCell cellExpiry=new DataGridViewTextBoxCell();
                    cellExpiry.Value = cookie.Expires;
                    dr.Cells.Add(cellExpiry);
                    rows2.Add(dr);
                }
            }
            new DataGridViewUpdator(this.dv_Cookies, rows2.ToArray(), false);
        }

        void _WebReqEngine_OnIntercepterStatusChanged(bool started)
        {
            if(started)
            {
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Traffic,
                                           SystemColors.Control, true, "Started",
                                           this.imageList1.Images[3]);

                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test1,
                                           SystemColors.Control, true, true, "Started",
                                           this.imageList1.Images[0]);
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test2,
                                           SystemColors.Control, true, true, "Started",
                                           this.imageList1.Images[0]);
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test3,
                                           SystemColors.Control, true, true, "Started",
                                           this.imageList1.Images[0]);
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test4,
                                           SystemColors.Control, true, true, "Started",
                                           this.imageList1.Images[0]);
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test5,
                                           SystemColors.Control, true, true, "Started",
                                           this.imageList1.Images[0]);
               // this.btn_Traffic.Image = this.imageList1.Images[3];
            }
            else
            {
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Traffic,
                                           SystemColors.Control, true, "Stopped",
                                           this.imageList1.Images[4]);

                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test1,
                                           SystemColors.Control, true, false, "Started",
                                           this.imageList1.Images[0]);
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test2,
                                           SystemColors.Control, true, false, "Started",
                                           this.imageList1.Images[0]);
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test3,
                                           SystemColors.Control, true, false, "Started",
                                           this.imageList1.Images[0]);
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test4,
                                           SystemColors.Control, true, false, "Started",
                                           this.imageList1.Images[0]);
                new ToolStripButtonUpdator(this.toolStrip1, this.btn_Test5,
                                           SystemColors.Control, true, false, "Started",
                                           this.imageList1.Images[0]);
            }
        }

        private void WebCrawlerEditor_Load(object sender, EventArgs e)
        {
            this.cbo_Protocol.Items.Clear();
            for(int i=0;i<=5;i++)
            {
                WebRequestProtocol protocol = (WebRequestProtocol) i;
                this.cbo_Protocol.Items.Add(protocol.ToString());
            }
            this.cbo_Protocol.SelectedIndex = 0;
        }

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        public object OwnerActivityNode
        {
            get { return _ownerActivityNode; }
            set { _ownerActivityNode = value; }
        }

        public Type WorkflowComponentType
        {
            get { return typeof(WebCrawlerComponnet); }
        }

        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents,
                                 object activityNode, WorkflowComponentBase wfComponent)
        {
            this._ownerActivityNode = activityNode;
            this._WebCrawler = (WebCrawlerComponnet) wfComponent;
        }

        public void SaveSettings()
        {
            throw new NotImplementedException();
        }

        public TestResult Test()
        {
            throw new NotImplementedException();
        }

        private void btn_Go_Click(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(this.txt_Url.Text))
            {
                try
                {
                    WebRequest webRequest = new WebRequest();
                    string baseUrl = string.Empty;
                    string pageUrl = string.Empty;
                    List<WebParameter> parameters = new List<WebParameter>();
                    this._WebReqEngine.ParseUrl(this.txt_Url.Text, ref baseUrl, ref pageUrl, ref parameters);
                    webRequest.BaseUrl = baseUrl;
                    webRequest.Cookies = new List<Cookie>();
                    webRequest.Credential = new NetworkCredential();
                    webRequest.Parameters = parameters;
                    webRequest.RequestPagePath = pageUrl;
                    webRequest.WebRequestID = Guid.NewGuid();
                    webRequest.Protocol = (WebRequestProtocol) this.cbo_Protocol.SelectedIndex;
                    WebResponse webResponse = this._WebReqEngine.GetWebResponse(webRequest);
                    this.ie_Response.Navigate(webResponse.CachedContentFilePath);

                    this.dv_Parameters.Rows.Clear();
                    if(parameters !=null && parameters.Count>0)
                    {
                        foreach(WebParameter webParameter in parameters)
                        {
                            DataGridViewRow dr=new DataGridViewRow();
                            DataGridViewTextBoxCell cellName=new DataGridViewTextBoxCell();
                            cellName.Value = webParameter.ParameterName;
                            dr.Cells.Add(cellName);
                            DataGridViewTextBoxCell cellValue=new DataGridViewTextBoxCell();
                            cellValue.Value = webParameter.ParameterValue;
                            dr.Cells.Add(cellValue);
                            DataGridViewComboBoxCell cellType=new DataGridViewComboBoxCell();
                            for(int i=0;i<=5;i++)
                            {
                                WebParameterType webParamType = (WebParameterType) i;
                                cellType.Items.Add(webParamType.ToString());
                            }
                            cellType.Value = webParameter.ParemeterType.ToString();
                            dr.Cells.Add(cellType);
                            this.dv_Parameters.Rows.Add(dr);
                        }
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

        private void btn_Power_Click(object sender, EventArgs e)
        {
            if (this._WebReqEngine.Started)
            {
                this._WebReqEngine.Stop();
            }
            else
            {
                this._WebReqEngine.Start();
            }
        }
    }
}
